package config

import (
	"fmt"
	_ "fmt"
	"gopkg.in/yaml.v3"
	_ "gopkg.in/yaml.v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	_ "os"
	"path/filepath"
	"runtime"
)

type Config struct {
	Mysql struct {
		User, Password, Host, Dbname, Options string
		Port, MaxOpen                         int
	}
}

var DB *gorm.DB

func InitMysql() {
	var config Config

	ex, _ := os.Executable()
	exPath := filepath.Dir(ex)

	// 2. 需要软链追踪再补一句
	realPath, _ := filepath.EvalSymlinks(ex)

	_, filename, _, _ := runtime.Caller(0) // 0 = 当前调用栈
	fmt.Println("path:", filepath.Dir(filename))

	fmt.Println("exPath:", exPath)
	fmt.Println("realPath:", realPath)
	//fmt.Println()
	exePath, _ := filepath.Abs(os.Args[0])
	fmt.Println("path:" + exePath)

	file, err := os.ReadFile(filepath.Dir(filename) + string(filepath.Separator) + "config.yml")
	if err != nil {
		panic(err)
	} else if err := yaml.Unmarshal(file, &config); err != nil {
		panic(err)
	}
	DB = loadDB(&config)
}

func loadDB(mm *Config) *gorm.DB {
	// root:123456@tcp(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4", mm.Mysql.User,
		mm.Mysql.Password, mm.Mysql.Host, mm.Mysql.Port, mm.Mysql.Dbname)

	fmt.Println("dsn:", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		PrepareStmt: true,
	})
	if err != nil {
		panic(err)
	}
	sqlDB, err := db.DB()
	if err != nil {
		panic(err)
	}
	sqlDB.SetMaxIdleConns(mm.Mysql.MaxOpen)
	return db
}
